package com.tidc.seaservermodel.util;

import com.tidc.seaservermodel.exception.TidcBadParent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020-3-28 21:02
 * @description：
 * @modified By：
 * @version:
 */
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    public static Map<Object, Object> pagingPrepare(int pageSize,int pageNum,int count) throws TidcBadParent {
        Map<Object, Object> map = new HashMap<>();
        if (pageNum <= 0 || pageSize <= 0 ) {
            throw new TidcBadParent("页数和数量不正确");
        }
        int i = count / pageSize;
        i = count-(pageSize*i) == 0? i:++i;
        i = i == 0 ? 1 : i;
        map.put("pageNum", i); //最大有多少页
        map.put("total", count);
        return map;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContext配置成功");
        log.info("ApplicationContext配置成功");
    }
    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}
